package com.hc;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

//权限控制切面类
@Component
@Aspect
@Order(1)
public class PermissionAspect {

    @Around("execution(* com.hc.UserHelper.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        //获取目标对象的类型
        Class target =  joinPoint.getTarget().getClass();
        //获取目标方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取目标方法名称
        String name = methodSignature.getName();
        //方法参数类型
        Class[] argsClass = methodSignature.getParameterTypes();
        //获取目标方法
        Method method = target.getMethod(name,argsClass);
        //判断方法是否有指定注解
        if(method.isAnnotationPresent(PermissionAnno.class)){
            PermissionAnno permissionAnno = method.getAnnotation(PermissionAnno.class);
            String value = permissionAnno.value();
            List<String> permissionList = PermissionUtil.getPermissionList();
            if(!permissionList.isEmpty() && permissionList.contains(value)){
                System.out.println("有权限放行");
                result = joinPoint.proceed();
            }else{
                System.out.println("没有权限,不调用目标方法1");
            }
        }else{
            System.out.println("没有权限,不调用目标方法2");
        }
        return result;
    }
}
